import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 读取入站数据，监听接受数据事件，将数据打印后丢弃。
 * </p>
 *
 * @author tao
 * @date 2022/01/17
 */
public class FileUploadHttpRequestPrintServerHandler extends SimpleChannelInboundHandler<ByteBuf> {


    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadHttpRequestPrintServerHandler.class);

    /**
     * 每当从客户端收到新的数据时，这个方法会在收到消息时被调用.
     *
     * @param ctx 隧道处理器上下文
     * @param msg 接受的消息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

        LOGGER.info("接受到客户端传来的数据：{}", System.lineSeparator());
        if (msg.hasArray()) {
            ByteBuf heapBuf = msg;
            byte[] array = heapBuf.array();
            int offset = heapBuf.arrayOffset() + heapBuf.readerIndex();                //3
            int length = heapBuf.readableBytes();
            LOGGER.info(new String(array, offset, length, StandardCharsets.UTF_8));
        } else {
            ByteBuf directBuffer = msg;
            int length = directBuffer.readableBytes();
            byte[] bytes = new byte[length];
            directBuffer.getBytes(directBuffer.readerIndex(), bytes);
            LOGGER.info(new String(bytes, StandardCharsets.UTF_8));
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 当出现异常就关闭连接
        LOGGER.error("服务端处理器发生异常", cause);
        LOGGER.error("channel关闭", cause);
        ctx.channel().close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        String responseHtml = "<html><head><title>响应</title></head><body>响应成功</body></html>";
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.copiedBuffer(responseHtml, StandardCharsets.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        ctx.writeAndFlush(response).addListeners(ChannelFutureListener.CLOSE);
    }
}
